#include "StdAfx.h"
#include "FilterManager.h"
#include "utils.h"
#include <unordered_map>
#include <regex>
#include <iterator>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <memory>
#include <vector>

using namespace std;

CFilterManager::CFilterManager(void)
	:	SHORTCUTS_SIZE(8)
{
}

CFilterManager::~CFilterManager(void)
{
}

void CFilterManager::AddFilterList(shared_ptr<CFilterList> newFilterList)
{
	_filterLists.push_back(newFilterList);
}

vector<shared_ptr<CElementHidingCollection>> CFilterManager::GetElementHidingCollections()
{
	vector<shared_ptr<CElementHidingCollection>> ret;
	for(auto it = _filterLists.begin(); it != _filterLists.end(); ++it)
	{
		ret.push_back((*it)->GetElementHidingCollection());
	}
	
	return ret;
}

bool CFilterManager::MatchAdvertFilter(const wstring& srcElement)
{
	if( MatchFiltersWithShortcuts(srcElement) )
	{
		return true;
	}
	else
	{
		return MatchFiltersWithoutShortcuts(srcElement);
	}
}

bool CFilterManager::MatchFiltersWithShortcuts(const wstring& srcElement)
{
	if(srcElement.size() < SHORTCUTS_SIZE)
		return false;

	for(unsigned int i = 0; i <= srcElement.size() - SHORTCUTS_SIZE; ++i)
	{
		wstring wsub(srcElement.begin() + i, srcElement.begin() + i + SHORTCUTS_SIZE);
		//wstring wsub = toStdWString(sub);

		for(auto it = _filterLists.begin(); it != _filterLists.end(); ++it)
		{
			auto& filters = (*it)->GetFiltersWithShortcuts();			
			if(filters.count(wsub) == 1) //if is in hashtable
			{
				const wregex& filterRegex = filters[wsub].GetRegex();
				if(regex_search(srcElement.begin(), srcElement.end(), filterRegex))
					return true;
			}
		}
	}
	return false;
}

bool CFilterManager::MatchFiltersWithoutShortcuts(const wstring& srcElement)
{
	for(auto it = _filterLists.begin(); it != _filterLists.end(); ++it)
	{
		auto& filters = (*it)->GetFiltersWithoutShourtcuts();
		
		for(auto iterFilter = filters.begin(); iterFilter != filters.end(); ++iterFilter)
		{			
			bool isAdvert = regex_search(srcElement.begin(), srcElement.end(), iterFilter->GetRegex());
			if(isAdvert)
				return true;
		}
	}
	return false;
}

